//
//  QVerifyWebViewController.m
//  QWeiboSDK4iOSDemo
//
//  Created   on 11-1-14.
//   
//

#import "QVerifyWebViewController.h"

@implementation QVerifyWebViewController

@synthesize mWebView;
@synthesize _blockerView;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

	mWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0f, 44.0f, 320.0f, 440.0f)];
	mWebView.delegate = self;
    mWebView.backgroundColor = [UIColor clearColor];
	[self.view addSubview:mWebView];
    [mWebView release];
    
    _blockerView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 200, 60)];
	_blockerView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.8];
	_blockerView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
	_blockerView.alpha = 1.0;
	_blockerView.clipsToBounds = YES;
	_blockerView.layer.cornerRadius = 10;
    [self.view addSubview: _blockerView];
    [_blockerView release];
	
	UILabel	*label = [[UILabel alloc] initWithFrame: CGRectMake(0, 5, _blockerView.bounds.size.width, 15)];
	label.text = NSLocalizedString(@"加载中...", nil);
	label.backgroundColor = [UIColor clearColor];
	label.textColor = [UIColor whiteColor];
	label.textAlignment = UITextAlignmentCenter;
	label.font = [UIFont boldSystemFontOfSize: 15];
	[_blockerView addSubview: label];
    [label release];
	
	UIActivityIndicatorView	*spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
	
	spinner.center = CGPointMake(_blockerView.bounds.size.width / 2, _blockerView.bounds.size.height / 2 + 10);
	[_blockerView addSubview: spinner];
    [spinner release];
	[spinner startAnimating];    
}

- (IBAction)cancel:(id) sender 
{
    [[CQWeiBo DefaultQQwb] LoginCancel];
    [self dismissModalViewControllerAnimated:YES];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void)viewDidAppear:(BOOL)animated
{
    QWeiboSyncApi *api = [[[QWeiboSyncApi alloc] init] autorelease];
    NSString *retString = [api getRequestTokenWithConsumerKey:QQ_AppKey consumerSecret:QQ_AppSecret];    
    [[CQWeiBo DefaultQQwb] parseTokenKeyWithResponse:retString IsSave:NO];
    NSArray *arr = [retString componentsSeparatedByString:@"&"];
    
    if (0 == [[CQWeiBo DefaultQQwb].m_strTokenKey length])
    {
        NSArray *sub = [[arr objectAtIndex:0] componentsSeparatedByString:@"="];
        retString = [sub objectAtIndex:1];
        [CQWeiBo DefaultQQwb].m_strTokenKey   = retString;
        //NSLog(@"%@", retString);
        
        sub = [[arr objectAtIndex:1] componentsSeparatedByString:@"="];
        retString = [sub objectAtIndex:1];
        [CQWeiBo DefaultQQwb].m_strTokenSecret= retString;
        //NSLog(@"%@", retString);
    }
    
    NSString *url  = [NSString stringWithFormat:@"%@%@", VERIFY_URL, [CQWeiBo DefaultQQwb].m_strTokenKey];
    
    //NSLog(@"%@", url);
    NSURL *requestUrl = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:requestUrl];
    
    [mWebView loadRequest:request];
}


- (void)dealloc 
{    
    mWebView.delegate = nil;
	[mWebView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: @""]]];
    
    [super dealloc];
}

#pragma mark -
#pragma mark private methods

-(NSString*) valueForKey:(NSString *)key ofQuery:(NSString*)query
{
	NSArray *pairs = [query componentsSeparatedByString:@"&"];
	for(NSString *aPair in pairs){
		NSArray *keyAndValue = [aPair componentsSeparatedByString:@"="];
		if([keyAndValue count] != 2) continue;
		if([[keyAndValue objectAtIndex:0] isEqualToString:key]){
			return [keyAndValue objectAtIndex:1];
		}
	}
	return nil;
}

#pragma mark -
#pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
	
	NSString *query = [[request URL] query];
	NSString *Verifier = [self valueForKey:@"oauth_verifier" ofQuery:query];
	
	if (Verifier && ![Verifier isEqualToString:@""]) 
    {
		QWeiboSyncApi *api = [[QWeiboSyncApi alloc] init];
		NSString *retString = [api getAccessTokenWithConsumerKey:QQ_AppKey
												  consumerSecret:QQ_AppSecret
												 requestTokenKey:[CQWeiBo DefaultQQwb].m_strTokenKey 
											  requestTokenSecret:[CQWeiBo DefaultQQwb].m_strTokenSecret
														  verify:Verifier];
        
		[[CQWeiBo DefaultQQwb] parseTokenKeyWithResponse:retString IsSave:YES];
        
        
        [self dismissModalViewControllerAnimated:YES];
        
        [[CQWeiBo DefaultQQwb] LoginQQWeiboSuc];
        
        [api release];

		return NO;
	}
    
	return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    (1.0 == _blockerView.alpha) ? (_blockerView.alpha = 0.0) : (_blockerView.alpha = 1.0);
}

@end
